#include "tcpserver.h"
#include <QThread>
#include <QList>

TcpSocket::TcpSocket(int socketdesc, QTcpSocket *parent):QTcpSocket(parent)
{
    this->setSocketDescriptor(socketdesc);
    connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(SocketError(QAbstractSocket::SocketError)));
}

TcpSocket::~TcpSocket()
{

}

//将会移进线程里面运行
void TcpSocket::ReadAndParseData()
{
    TcpSocket *socket = (TcpSocket *)sender();

    QByteArray byte = socket->readAll();

    qDebug() <<"recvstr=" << byte.toHex()<< socket->peerAddress() << socket->peerPort();
   // m_recvDataStr += recvStr;
    //对数据的处理
}

void TcpSocket::SocketError(QAbstractSocket::SocketError socketError)
{
    TcpSocket *socket = (TcpSocket*)sender();
    qDebug() << socket->socketDescriptor();
}

TcpServer::TcpServer(const QString ip,int port,QTcpServer *parent) : QTcpServer(parent)
{
    bool bsucc;
    if(ip.length()==0)
        bsucc = this->listen(QHostAddress::AnyIPv4,port);
    else
        bsucc = this->listen(QHostAddress(ip),port);

}
TcpServer::~TcpServer()
{
    this->close();
    QList<TcpSocket*>::iterator it = m_socketList.begin();
    for(;it!=m_socketList.end();)
    {
        TcpSocket *sock = *it;
        m_socketList.erase(it++);
        delete sock;
        sock = NULL;
    }
}

void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    TcpSocket *socket = new TcpSocket(socketDescriptor);
    connect(socket,SIGNAL(readyRead()),socket,SLOT(ReadAndParseData()));
    connect(socket,SIGNAL(disconnected()),this,SLOT(SocketDisconn()));

    QThread *thread = new QThread(socket);
    connect(socket,SIGNAL(disconnected()),thread,SLOT(quit()));
    socket->moveToThread(thread);
    thread->start();
    emit newConnection();
}

void TcpServer::SocketDisconn()
{
    TcpSocket *socket = (TcpSocket*)sender();
    QList<TcpSocket *>::iterator it = std::find(m_socketList.begin(),m_socketList.end(),socket);
    if(it !=m_socketList.end())
    {
        m_socketList.erase(it);
        delete socket;
        socket = NULL;
    }
}

